import Vue from "vue";

import { ACCESS_TOKEN, X_ACCESS_TOKEN } from "@/store/mutation-types";

const user = {
  state: {
    token: "",
    name: "",
    avatar: "",
    buttons: [], // 按钮权限
    allButtons: [], // 所有按钮权限
    admintype: "", // 是否是超管
    roles: [],
    info: {},
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
      //sessionStorage.setItem("roles", Json.stringify(roles));
    },
    SET_INFO: (state, info) => {
      state.info = info;
    },
    SET_BUTTONS: (state, buttons) => {
      state.buttons = buttons;
    },
    SET_ALL_BUTTONS: (state, allButtons) => {
      state.allButtons = allButtons;
    },
    SET_ADMINTYPE: (state, admintype) => {
      state.admintype = admintype;
    },
  },

  actions: {
    //获取当前登录用户的信息
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        Vue.prototype.request
          .get("/api/auth/getLoginUser")
          .then((res) => {
            commit("SET_NAME", res.data.name);
            commit("SET_AVATAR", res.data.avatar);
            commit("SET_ADMINTYPE", res.data.adminType);
            commit("SET_ROLES", res.data.roles);
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        Vue.prototype.request
          .post("/api/logout")
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            resolve(err);
          })
          .finally(() => {
            Vue.ls.remove(ACCESS_TOKEN);
            Vue.ls.remove(X_ACCESS_TOKEN);
          });
      });
    },
  },
};

export default user;
